<?php

namespace App\Http\Controllers\Wechat;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use EasyWeChat\Message\Text;
use EasyWeChat\Message\News;

use App\Models\Shop\Product, App\Models\Shop\Order, App\Models\Shop\Customer;
use EasyWeChat;
class WeChatController extends Controller
{
    /***
     * @return mixed
     * *  项目部署上线
     * 1. 基于之前安装的easyWeChat包并生成了配置文件WeChat.php，由于此文件是读取env文件，
     *    所以我们可以在env文件中设置token，用于验证微信与服务器项目是否对接上。
     * 2. 在中间件WeChat.php文件中设置用户session信息并在web.php中加上 wechat.oauth中间件同时核心里面注册该中间件
     *    在config文件夹中的WeChat.php文件中开启 OAuth 配置
     * 3. 在浏览器中输入你的域名测试得到结果：请在微信客户端打开链接即为成功。
     * 4. 在api.php中配置微信前端接口路由并创建控制器和方法，控制器里面写上测试代码如下：
     *      $server = EasyWeChat::server();
    $server->setMessageHandler(function ($message) {
    return 'hello word!';
    });
    return $server->serve();
     * 5. customer模型设置黑名单，过滤微信不需要的字段：如： protected $guarded = ['privilege', 'country', 'language'];
     * 6. 修改微信公众平台测试号中的接口配置信息，例如：URL：http://test.hdjzq.top/api/wechat  Token:自定义
     * 7. 现在可以打开微信扫描测试号二维码，发送任意消息，查看是否有回复信息，最后设置各种事件，查询需要的数据
     */
    public function serve()
    {
        // 从项目实例中得到服务端应用实例。
        $server = EasyWeChat::server();
        $server->setMessageHandler(function ($message) {
            if ($message->MsgType == 'event') {
                switch ($message->Event) {
                    //关注事件
                    case 'subscribe':
                        return new Text(['content' => '欢迎关注刘玉龙小卖部~']);
                        break;

                    //点击事件
                    case 'CLICK':
                        //return $message->EventKey;

                        switch ($message->EventKey) {

                            case 'recommend':
                                return $this->is_recommend();
                                break;

                            case 'new':
                                return $this->is_new();
                                break;

                            case 'hot':
                                return $this->is_hot();
                                break;

                            case 'order':
                                return $this->order($message->FromUserName);
                                break;

                        }
                        break;
                }
            }

            //文本消息
            if ($message->MsgType == 'text') {
                switch ($message->Content) {
                    case '精选':
                    case '推荐':
                    case '精选推荐':
                    case 'recommend':
                        return $this->is_recommend();
                        break;

                    case '新品':
                    case '新品到货':
                    case 'new':
                        return $this->is_new();
                        break;

                    case '人气':
                    case '热卖':
                    case '人气热卖':
                    case 'hot':
                        return $this->is_hot();
                        break;

                    case '我的订单':
                    case '订单':
                    case 'order':
                        return $this->order($message->FromUserName);
                        break;

                    default:
                        return $this->default_msg();
                }
            }

            //语音消息
            if ($message->MsgType == 'voice') {
                switch ($message->Recognition) {
                    case '精选。':
                    case '推荐。':
                    case '精选推荐。':
                        return $this->is_recommend();
                        break;

                    case '新品。':
                    case '新品到货。':
                        return $this->is_new();
                        break;

                    case '人气。':
                    case '热卖。':
                    case '人气热卖。':
                        return $this->is_hot();
                        break;

                    case '订单。':
                    case '我的订单。':
                        return $this->order($message->FromUserName);
                        break;

                    default:
                        return '您说的是:' . $message->Recognition . '?';
                }
            }
        });
        return $server->serve();
    }

    /**
     * 精选推荐
     * @return array
     */
    private function is_recommend()
    {
        $products = Product::where('is_recommend', true)
            ->orderBy('is_top', "desc")
            ->orderBy('created_at')
            ->take(6)
            ->get();
//        return $products;

        $news = [];
        foreach ($products as $p) {
            $news[] = new News([
                'title' => $p->name,
                'description' => $p->description,
                'url' => 'http://test.hdjzq.top' . '/product/' . $p->id,
                'image' => $p->image ? $p->image : '',
            ]);
        }
        return $news;
    }

    /**
     * 人气热卖
     * @return array
     */
    private function is_hot()
    {
        $products = Product::where('is_hot', true)
            ->orderBy('is_top', "desc")
            ->orderBy('created_at')
            ->take(6)
            ->get();

        $news = [];
        foreach ($products as $p) {
            $news[] = new News([
                'title' => $p->name,
                'description' => $p->description,
                'url' => 'http://wechat.hdjzq.top' . '/product/' . $p->id,
                'image' => $p->image ? $p->image : '',
            ]);
        }
        return $news;
    }

    /**
     * 新品
     * @return array
     */
    private function is_new()
    {
        $products = Product::where('is_new', true)
            ->orderBy('is_top', "desc")
            ->orderBy('created_at')
            ->take(6)
            ->get();

        $news = [];
        foreach ($products as $p) {
            $news[] = new News([
                'title' => $p->name,
                'description' => $p->description,
                'url' => 'http://wechat.hdjzq.top' . '/product/' . $p->id,
                'image' => $p->image ? $p->image : '',
            ]);
        }
        return $news;
    }

    /**
     * 我的订单
     * @param $openid
     * @return array|string
     */
    function order($openid)
    {
        $customer = Customer::where('openid', $openid)->first();

        //如果用户还不存在,直接返回
        if (!$customer) {
            return '你没有完成的订单, 马上去购物吧~';
        }

        $order_status = config('admin.order_status');
        $orders = Order::where('status', '<', 5)
            ->where('customer_id', $customer->id)
            ->with('order_products.product')
            ->orderBy('status')
            ->orderBy('id', 'desc')
            ->take(6)
            ->get();

        if ($orders->isEmpty()) {
            return '你没有完成的订单, 马上去购物吧~';
        }

        $news = [];
        foreach ($orders as $order) {
            $news[] = new News([
                'title' => '订单号' . $order->id . " (" . $order_status[$order->status] . ")",
                'url' => 'http://wechat.hdjzq.top' . '/order/' . $order->id,
                'image' => $order->order_products->first()->product->image ? $order->order_products->first()->product->image : '',
            ]);
        }
        return $news;
    }

    /**
     * 默认消息
     * @return string
     */
    function default_msg()
    {
        return '您想说点什么~';
    }
}
